package com.cn.ccp.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.cn.ccp.bean.FilePathBean;
import com.cn.ccp.bean.UserBean;
import com.cn.ccp.service.course.FilePathService;
import com.cn.ccp.service.system.UserService;
import com.cn.ccp.util.CCPContants;
import com.cn.ccp.util.Converter;

@SuppressWarnings("serial")
public class LoadImageServlet extends HttpServlet {
	
	
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String userId = request.getParameter("uid");
		String fileName = request.getParameter("fileName");
		String deleteFileName = request.getParameter("deleteFileName");
		if(userId != null  && !userId.equals("")){
			UserBean bean = new UserBean();
			ServletContext servletContext = this.getServletContext(); 
			 WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);  
		     UserService userServices = (UserService) ctx.getBean("userService") ;
		     bean = userServices.findById(Integer.parseInt(userId));
		     if(bean.getImage() != null && !bean.getImage().equals("") && bean.getFile_path_id() != -1 && !bean.getImage().equals(fileName)){
		    	 long time = System.currentTimeMillis() ;
		    	 FilePathService filePathService = (FilePathService) ctx.getBean("filePathService");
		    	 
		    	 File oldFile = new File(CCPContants.SYS_PATH  + deleteFileName);
		    	 oldFile.delete();
		    	 
		    	 
		    	 
				try {
					String ext = bean.getImage().split("\\.")[1];
					File des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+bean.getId() + File.separator +"head-image"+time+"."+ext);
					des.delete();
					
					FilePathBean fpbean = filePathService.findFilePathById(bean.getFile_path_id());
					if(bean != null){
						CCPContants.copyFile(fpbean.getPath()+bean.getImage(), des.getPath());
						
						bean.setHeadImage("tempfile/"+bean.getId()+"/"+"head-image"+time+"."+ext);
						response.getWriter().print(bean.getHeadImage()+","+bean.getImage());
						
					}
				} catch (Exception e) {
					return ;
				}
		     }
		}
		
		String type = request.getParameter("type");
			if(type != null && !type.equals("") && !type.equals("null")){
			String filename = "";
			if(type.equalsIgnoreCase("student")){
				filename = "学生数据模板";
			}else{
				filename = "教师数据模板";
			}
			String path = System.getProperty("webapp.root")+"tempfile/"+filename + ".xls";
			
			
			File file = new File(path);
	
			if (file.exists()) {
				try {
					response.setContentType("application/octet-stream");
					System.out.println("downloading file:" + path);
					RequestDispatcher rd = request.getRequestDispatcher(path);
					response.setCharacterEncoding("GB2312");
					String fname = new String(file.getName().getBytes("GBK"), "ISO8859-1");
					response.setHeader("Content-Disposition", "attachment; filename=\"" + fname + "\"");
					response.setHeader("content-type", "application/octet-stream");
					rd.forward(request, response);
					System.out.println("用户开始下载。");
				} catch (Exception e) {
					System.out.println(e);
					System.out.println("用户取消下载。");
				}
			} else {
				System.out.println("文件不存在:" + path);
				response.setContentType("text/html");
				response.setCharacterEncoding("UTF-8");
				PrintWriter out = response.getWriter();
				out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
				out.println("<HTML>");
				out.println(" <HEAD><TITLE>错误</TITLE>");
				out.println("</HEAD>");
				out.println(" <BODY>");
				out.println("<p><span class=\"error\">文件不存在！</span></p>");
				out.println(" </BODY>");
				out.println("</HTML>");
				out.flush();
				out.close();
			}
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
}
